<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" >

      <el-form-item>
        <el-button v-if="isAuth('funds:receiptdetail:save')" type="primary" @click="addRow">新增</el-button>
        <el-button v-if="isAuth('funds:receiptdetail:delete')" type="danger" @click="deleteHandle()"
                   :disabled="dataListSelections.length <= 0">批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      :summary-method="getSummaries"
      show-summary
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%; margin-top: 20px">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>

      <el-table-column
        prop="saleOrderName"
        header-align="center"
        align="center"
        width="250px"
        label="销售订单">
        <template slot-scope="scope">
          <el-autocomplete v-if="scope.row.status" v-model="scope.row.saleOrderName"
                           :fetch-suggestions="querySearchAsync" placeholder="请输入内容"
                           @select="handleNameSelect($event, scope.row)"
                           popper-class="select-option"
          ></el-autocomplete>
          <span v-else>{{scope.row.saleOrderName}}</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="saleDate"
        header-align="center"
        align="center"
        label="销售日期">
      </el-table-column>
      <el-table-column
        prop="totalAmount"
        header-align="center"
        align="center"
        label="单据金额">
      </el-table-column>
      <el-table-column
        prop="deposit"
        header-align="center"
        align="center"
        label="定金">
      </el-table-column>
      <el-table-column
        prop="writtenOffAmount"
        header-align="center"
        align="center"
        label="已核销金额">
      </el-table-column>
      <el-table-column
        prop="remainAmount"
        header-align="center"
        align="center"
        label="未核销金额">
      </el-table-column>
      <el-table-column
        prop="writtenOffNum"
        header-align="center"
        align="center"
        label="已核销次数">
      </el-table-column>
      <el-table-column
        prop="thisWrittenOffAmount"
        header-align="center"
        align="center"
        label="本次核销金额">
        <template slot-scope="scope">
          <el-input v-if="scope.row.status" v-model="scope.row.thisWrittenOffAmount"
                    @keyup.native="scope.row.thisWrittenOffAmount = oninputMoney(scope.row.thisWrittenOffAmount)"
          ></el-input>
          <span v-else>{{scope.row.thisWrittenOffAmount}}</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="remark"
        header-align="center"
        align="center"
        label="备注">
        <template slot-scope="scope">
          <el-input v-if="scope.row.status" v-model="scope.row.remark"
          ></el-input>
          <span v-else>{{scope.row.remark}}</span>
        </template>

      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
<!--          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>-->
<!--          <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>-->
          <el-button class="el-icon-edit" type="primary" :disabled="scope.row.status"
                     size="small" circle @click.native.prevent="editRow(scope.row)"></el-button>
          <el-button class="el-icon-delete" type="danger"
                     size="small" circle @click.native.prevent="deleteRow(scope.$index, dataList)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
<!--    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>-->
  </div>
</template>

<script>
  import AddOrUpdate from './receiptdetail-add-or-update'
  export default {
    data () {
      return {
        dataForm: {
          headerId: 0,
          key: ''
        },
        formDto: {
          receiptDetailList: [],
          deleteReceiptDetailList: []
        },
        dataList: [],
        delList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        thisWrittenOffAmount: 0,
        clientId: ''
      }
    },
    components: {
      AddOrUpdate
    },
    activated () {
      // this.getDataList()
      this.getReceiptDetailsByHeadId(this.dataForm.headerId)
    },
    methods: {
      // 获取数据列表
      getReceiptDetailsByHeadId (id) {
        this.dataForm.headerId = id || 0
        this.dataListLoading = true
        this.delList = []
        this.$http({
          url: this.$http.adornUrl('/funds/receiptdetail/listAllByHeadId'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'headId': id
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/funds/receiptdetail/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      // 删除该行
      deleteRow (index, rows) {
        this.delList.push(rows[index].id)
        rows.splice(index, 1)
      },
      editRow (row) {
        row.status = 1
      },
      // 新增一行
      addRow () {
        this.dataList.push({
          thisWrittenOffAmount: 0,
          status: 1
        })
      },

      // 销售订单 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      querySearchAsync (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null || queryString === 'undefined' ? '' : queryString
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/sales/orderheader/listSaleOrders`),
          method: 'get',
          params: this.$http.adornParams({
            'name': this.s_girard,
            'clientId': this.clientId
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.names = data.saleOrdersMap.saleOrderNameDtoList
          } else {
            this.names = []
          }
        })
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.names)
        }, 1000)
        // callback(this.names)
      },
      handleNameSelect (item, row) {
        console.log(item)
        row.saleOrderName = item.saleOrderName
        row.salesOrderHeaderId = item.salesOrderHeaderId
        row.saleOrderCode = item.saleOrderCode
        row.deposit = item.deposit
        row.writtenOffAmount = item.writtenOffAmount
        row.remainAmount = item.remainAmount
        row.saleDate = item.saleDate
        row.thisWrittenOffNum = item.thisWrittenOffNum
        row.writtenOffNum = item.writtenOffNum
        row.totalAmount = item.totalAmount
      },
      // 合计
      getSummaries (param) {
        const {columns, data} = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 1) {
            sums[index] = '合计'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          // 本次核销金额(元)
          if (column.property === 'thisWrittenOffAmount') {
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              sums[index] += ''
            } else {
              sums[index] = ''
            }

            sums[index] = parseFloat(sums[index]).toFixed(2)

            this.thisWrittenOffAmount = sums[index]
          }
        })

        return sums
      },
      oninputMoney (num) {
        let str = num
        let len1 = str.substr(0, 1)
        let len2 = str.substr(1, 1)
        // 如果第一位是0，第二位不是点，就用数字把点替换掉
        if (str.length > 1 && len1 === 0 && len2 !== '.') {
          str = str.substr(1, 1)
        }
        // 第一位不能是.
        if (len1 === '.') {
          str = ''
        }
        // 限制只能输入一个小数点
        if (str.indexOf('.') !== -1) {
          let str_ = str.substr(str.indexOf('.') + 1)
          if (str_.indexOf('.') !== -1) {
            str = str.substr(0, str.indexOf('.') + str_.indexOf('.') + 1)
          }
        }
        // 正则替换
        str = str.replace(/[^\d.]/g, '') // 保留数字和小数点
        str = str.replace(/\.\d\d\d$/, '') // 小数点后只能输两位
        return str
      }
    }
  }
</script>
